#include <QApplication>
#include <QLabel>
#include <QString>
#include "rclcpp/rclcpp.hpp"
#include "status_interfaces/msg/system_status.hpp"

using std::placeholders::_1;

class SysStatusDisplay: public rclcpp::Node
{
private:
    rclcpp::Subscription<status_interfaces::msg::SystemStatus>::SharedPtr m_status_subscriber;
    QLabel* m_label;

public:
    explicit SysStatusDisplay(const std::string& name):Node(name)
    {
        RCLCPP_INFO(this->get_logger(),"这是一个SysStatusDisplay节点");
        m_label = new QLabel();
        m_status_subscriber = this->create_subscription<status_interfaces::msg::SystemStatus>("sys_status",10,std::bind(&SysStatusDisplay::sys_status_callback,this,_1));
        m_label->setText(get_qstr_from_msg(std::make_shared<status_interfaces::msg::SystemStatus>()));
        m_label->show();
    }

    void sys_status_callback(const status_interfaces::msg::SystemStatus::SharedPtr msg)
    {
       
        m_label->setText(get_qstr_from_msg(msg));
        
    }

    QString get_qstr_from_msg(const status_interfaces::msg::SystemStatus::SharedPtr msg)
    {
        std::stringstream ss;
        ss << "===============新提供状态可视化工具===============\n" 
        << "数 据 时 间:\t " << msg->time_stamp.sec<<"\ts"
        << "\n主 机 名 称:\t" << msg->host_name
        << "\nCPU 使用率:\t" << msg->cpu_percent << "\t%"
        << "\n内存使用率:\t" << msg->memory_percent << "\t%"
        << "\n内存总大小:\t" << msg->memory_total << "\tMB"
        << "\n剩余可用内存:\t" << msg->memory_available << "\tMB"
        << "\n网络发送量:\t" << msg->net_send << "\tMB"
        << "\n网络接收量:\t" << msg->net_recv << "\tMB"
        << "===================================================\n";
        return QString::fromStdString(ss.str());
    }
};

int main(int argc,char** argv)
{
    rclcpp::init(argc,argv);
    QApplication app(argc,argv);
    auto node = std::make_shared<SysStatusDisplay>("sys_status_display");
    std::thread t([&](){
        rclcpp::spin(node);
    });
    t.detach();
    app.exec();
    rclcpp::shutdown();
    return 0;
}